import {reqGetCode,reqUserRegister,reqUserLogin,reqUserInfo,reqLogout} from "../../api"

const actions = {
	//获取验证码
	async getCodeText({commit},phone){
		//这里result中的data是测试用的，正常开发是后台发送到手机中
		let result = await reqGetCode(phone)
		console.log(result)
		if(result.code==200){
			commit('GETCODETEXT',result.data)
			return 'ok'
		}else{
			return Promise.reject(new Error('失败了'))
		}
	},
	//用户注册
	async userRegister({commit},user){
		let result = await reqUserRegister(user)
		console.log(result)
		if(result.code==200){
			return 'ok'
		}else{
			return Promise.reject(new Error('faile'))
		}
	},
	//用户登录
	async userLogin({commit},user){
		let result = await reqUserLogin(user)
		// console.log(result)
		if(result.code==200){
			commit('USERLOGIN',result.data)
			//用户成功登陆，存储TOKEN到本地，这样仓库里的token就能获取本地信息
			localStorage.setItem('TOKEN',result.data.token)
			return 'ok'
		}else{
			return Promise.reject(new Error('faile'))
		}
	},
	//获取用户信息
	async getUserInfo({commit}){
		let result = await reqUserInfo()
		// console.log(result)
		if(result.code==200){
			commit('GETUSERINFO',result.data)
			return 'ok'
		}else{
			return Promise.reject(new Error('faile'))
		}
	},
	async userLogout({commit}){
		let result = await reqLogout()
		if(result.code==200){
			console.log(result)
			commit('USERLOGOUT')
		}
	}
	
}
const mutations = {
	//验证码
	GETCODETEXT(state,codeText){
		state.codeText = codeText
		console.log(codeText)
	},
	//token
	USERLOGIN(state,userInfo){
		state.token = userInfo.token
	},
	//获取用户信息
	GETUSERINFO(state,userInfo){
		state.userInfo = userInfo
	},
	//退出登录
	USERLOGOUT(state){
		//清除仓库中的用户信息
		state.userInfo = {}
		state.token = ''
		//清除本地存储中的TOKEN
		localStorage.removeItem('TOKEN')
	}
}
const state = {
	codeText:'',
	token:localStorage.getItem('TOKEN'),
	userInfo:{}
}
const getters = {
	
}

export default {
	state,
	mutations,
	actions,
	getters
}
